<template>
  <div class="MyNeed">
    <div class="MyNeed-title">
      <span>我的需求</span>
      <span class="add-btn">
        <a-button type="primary" @click="add" ghost>发布需求</a-button>
      </span>
    </div>
    <div class="mt-10 card-box">
      <a-form layout="inline" class="clearfix" :form="form" @submit="handleSubmit">
        <a-form-item label="关键字：">
          <a-input placeholder="请输入需求名称或需求编号" v-decorator="['keyword']" />
        </a-form-item>
        <a-form-item label="需求状态：">
          <a-select style="width: 120px" @change="handleChange" v-decorator="['demandStatus']" placeholder="请选择">
            <a-select-option value="">请选择</a-select-option>
            <a-select-option v-for="item in demandStatus" :value="item.key" :key="item.key">{{ item.label }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="是否过期：">
          <a-select style="width: 120px" @change="handleChange" v-decorator="['expiredType']" placeholder="请选择">
            <a-select-option value="">请选择</a-select-option>
            <a-select-option v-for="item in isOverdue" :value="item.key" :key="item.key">{{ item.label }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="审核状态：">
          <a-select style="width: 120px" @change="handleChange" v-decorator="['auditStatus']" placeholder="请选择">
            <a-select-option value>请选择</a-select-option>
            <a-select-option v-for="item in auditStatu" :value="item.key" :key="item.key">{{ item.label }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="更新时间">
          <a-range-picker @change="onChange" :placeholder="['开始日期', '结束日期']" v-decorator="['creatDate']">
            <a-icon slot="suffixIcon" type="calendar" />
          </a-range-picker>
        </a-form-item>
        <a-form-item label="截止日期">
          <a-range-picker @change="onChange1" :placeholder="['开始日期', '结束日期']" v-decorator="['endDate']">
            <a-icon slot="suffixIcon" type="calendar" />
          </a-range-picker>
        </a-form-item>
        <div class="f-right mt-8">
          <a-button class="mr-8" style="color:#909399;" @click="clear">重置</a-button>
          <a-button type="primary" html-type="submit">搜索</a-button>
        </div>
      </a-form>
    </div>

    <div class="action">
      <a-table :scroll="{ x: 1500}" :columns="columns" :data-source="materialsDemand" :pagination="ipagination" :rowKey="record=>record.id">
        <div slot="demandStatusName" slot-scope="text" style="color: #E9284F;" v-if=" text == '未解决'">未解决</div>
        <div slot="demandStatusName" slot-scope="text" style="color: #0DA9B0;" v-else-if=" text == '已解决'">已解决</div>
        <div slot="demandStatusName" slot-scope="text" style="color: #EE6224;" v-else-if=" text == '已过期'">已过期</div>

        <div slot="auditStatus" slot-scope="text" style="color: #E9284F;" v-if=" text == 1">审核中</div>
        <div slot="auditStatus" slot-scope="text" style="color: #0DA9B0;" v-else-if=" text == 2">已通过</div>
        <div slot="auditStatus" slot-scope="text" style="color: #EE6224;" v-else-if=" text == 3">未通过</div>

        <div slot="matchStatus" slot-scope="text" style="color: #0DA9B0;" v-if=" text == 1">已匹配</div>
        <div slot="matchStatus" slot-scope="text" style="color: #EE6224;" v-else-if=" text == 2">未匹配</div>
        <template slot="handle" slot-scope="text,recode">
          <a @click="showInformation(recode)">详情</a>
          <a-divider type="vertical" />
          <a @click="operation(recode)">编辑</a>
        </template>
        <a slot="name" slot-scope="text">{{ text }}</a>
        <span slot="action" slot-scope="text,record" class="operate-cls">
          <a @click="seeEdit(record)">查看详情</a>
          <a @click="seeReco(record)" v-if="record.auditStatus === 2">查看推送</a>
          <a v-show="record.ishandleEdit" @click="handleEdit(record)">编辑</a>
          <!-- 是否匹配 - 弹框版 -->
          <a @click="isMatch(record)" v-if="record.auditStatus === 2">是否匹配</a>
          <!-- 是否匹配 - 气泡框版 -->
          <!-- <a-popconfirm title="是否匹配?" ok-text="匹配" cancel-text="不匹配" @confirm="match(record, 1)" @cancel="match(record, 2)">
            <a class="ml-20" v-if="record.auditStatus === 2">是否匹配</a>
          </a-popconfirm> -->
          <a v-show="record.isdeleEdit"  @click="deleEdit(record)">删除</a>
          <a v-show="record.isEdit" @click="Edit(record)">解决</a>
        </span>
      </a-table>
      <!-- <a-modal v-model="visible" title="删除需求" @ok="handleOk">
        <p>是否确认删除该需求？</p>
        <br>
        <a-checkbox  v-if="Status=='已过期' && auditStatus==2" :checked="checkNick" @change="handleChange1">
          该需求已解决
        </a-checkbox>
      </a-modal> -->
    </div>
    <a-modal title="推荐企业" :visible="recoVis" :footer="null" @cancel="cancelRec">
      <a-table :rowKey="record=>record.entId" :columns="matchColumns" :data-source="recommCompanyInfo" bordered :pagination="false" :showHeader="false">
        <a slot="entName" slot-scope="text, record" target="_blank" title="点击可查看企业详情"
          :href="`${webHref}/aupply-chains-14-16203/entdetails?id=${record.entId}`">{{ text }}</a>
      </a-table>
    </a-modal>
    <a-modal title="匹配" :visible="matchVis" okText="匹配" cancelText="不匹配"
      @ok="match(1)" @cancel="match(2)" :maskClosable="false" :keyboard="false" :closable="false">
      <span>是否匹配该需求？</span>
    </a-modal>
    <!-- <Edit ref="Edit" :msg="EditId"></Edit> -->
  </div>
</template>

<script>
// import Edit from "./component/Edit.vue";
import { getEntBaseInfo } from "@/apis/user/EntBaseInfo";
import { setIsSign } from "@/utils/auth"; // get token from cookie
import {
  GetSearchPageList,
  deleteMaterialsDemand,
  updateDemandStatus,
  updateMatchStatusStatus,
  getProductEntPush
} from "@/apis/user/MaterialsDemand";
export default {
  // components: {
  //   Edit
  // },
  data() {
    return {
      recoVis: false,
      matchVis: false,
      materialsDemand: [],
      columns: [
        {
          title: "序号",
          dataIndex: "index",
          width: 80,
          align: "center",
          customRender: (text, record, index) =>
            `${(this.ipagination.current - 1) * 10 + index + 1}`, // 显示每一行的序
        },
        {
          title: "需求名称",
          dataIndex: "demandProductName",
          key: "demandProductName",
          // ellipsis: true,
        },
        {
          title: "需求编号",
          dataIndex: "demandNo",
          align: "center",
          //  ellipsis: true,
        },
        {
          title: "需求状态",
          dataIndex: "demandStatusName",
          align: "center",
          scopedSlots: { customRender: "demandStatusName" },
          //  ellipsis: true,
          // customRender:function (text,record,index) {
          //   if(text==1){
          //     return "已解决"
          //   }else if(text==2){
          //     return "未解决"
          //   }else if(text==3){
          //     return "已失效"
          //   }
          // }
        },
        {
          title: "审核状态",
          dataIndex: "auditStatus",
          align: "center",
          scopedSlots: { customRender: "auditStatus" },
          // ellipsis: true,
          // customRender:function (text) {
          //   if(text==1){
          //     return "审核中"
          //   }else if(text==2){
          //     return "已通过"
          //   }else if(text==3){
          //     return "未通过"
          //   }
          // }
        },
        {
          title: '是否匹配',
          dataIndex: 'matchStatus',
          align: 'center',
          scopedSlots: { customRender: 'matchStatus' }
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
          align: "center",
          //  ellipsis: true,
        },
        {
          title: "更新时间",
          dataIndex: "updateTime",
          align: "center",
          //  ellipsis: true,
        },
        {
          title: "截止日期",
          dataIndex: "isLongTime",
          align: "center",
          //  ellipsis: true,
          customRender: function (text, recode) {
            if (text == 1) {
              return "长期有效";
            } else if (text == 0 || text == null) {
              return recode.expirationDate;
            }
          },
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          fixed: "right",
          width: 200,
          scopedSlots: { customRender: "action" },
        },
      ],
      demandStatus: [
        {
          label: "已解决",
          key: 1,
        },
        {
          label: "未解决",
          key: 2,
        },
      ],
      isOverdue: [
        {
          label: "未过期",
          key: 1,
        },
        {
          label: "已过期",
          key: 2,
        },
      ],
      auditStatu: [
        {
          label: "审核中",
          key: 1,
        },
        {
          label: "已通过",
          key: 2,
        },
        {
          label: "未通过",
          key: 3,
        },
      ],
      ipagination: {
        total: 0,
        current: 1,
        pageSize: 10,
        pageSizeOptions: ["10", "20", "30", "40", "50"],
        showTotal: (total) => `共有 ${total} 条数据`,
        showQuickJumper: true,
        showSizeChanger: true,
        onShowSizeChange: (current, pageSize) =>
          this.onSizeChange(current, pageSize),
        onChange: (page, pageSize) => this.onPageChange(page, pageSize),
      },
      form: this.$form.createForm(this, { name: "dynamic_rule" }),
      formLine: {},
      webHref: location.origin,
      EditId: "",
      oldItem: null,
      userId: "",
      isSign: "",
      createTimeFrom: "",
      createTimeTo: "",
      expirationDateFrom: "",
      expirationDateTo: "",
      visible: false,
      checkNick: false,
      delID: "",
      Status: "",
      auditStatus: "",
      matchColumns: [
        {
          title: '企业名称',
          dataIndex: 'entName',
          scopedSlots: { customRender: 'entName' }
        }
      ],
      recommCompanyInfo: [],
      isMatchInfo: {}
    };
  },
  created() {
    this.getEntBaseInfo();
    setTimeout(() => {
      this.GetSearchPageList();
    }, 500);
  },
  methods: {
    //查看推送
    seeReco(record) {
      let requestData = {
        demandNo: record.demandNo === null ? '' : record.demandNo
      }
      getProductEntPush(requestData).then(res => {
        if(res && res.code === 200) {
          const { data } = res
          this.recommCompanyInfo = data
          this.recoVis = true
        }else {
          this.$message.error('查看失败')
        }
      }).catch(err => {
        if(err) {
          this.$message.error('服务器错误')
        }
      })
    },
    // 关闭推荐弹框
    cancelRec() {
      this.recoVis = false
    },
    // 打开是否匹配
    isMatch(record) {
      this.isMatchInfo = record
      this.matchVis = true
    },
    // 是否匹配 --- 弹框版
    match(status) {
      let data = {
        id: this.isMatchInfo.id,
        matchStatus: status
      }
      updateMatchStatusStatus(data).then(res => {
        if(res.code === 200) {
          this.$message.success('操作完成')
          this.GetSearchPageList()
          this.matchVis = false
        }else {
          this.$message.error('操作失败')
        }
      }).catch(err => {
        if(err) {
          this.$message.error('服务器错误')
        }
      })
    },
    // 是否匹配 --- 气泡框版
    // match(record, status) {
    //   let data = {
    //     id: record.id,
    //     matchStatus: status
    //   }
    //   updateMatchStatusStatus(data).then(res => {
    //     if(res.code === 200) {
    //       this.$message.success('操作完成')
    //       this.GetSearchPageList()
    //     }else {
    //       this.$message.error('操作失败')
    //     }
    //   }).catch(err => {
        //   if(err) {
        //     this.$message.error('服务器错误')
        //   }
        //  })
    // },
    //获取企业基本信息
    getEntBaseInfo() {
      getEntBaseInfo().then((res) => {
        console.log("获取企业信息");
        console.log(res);
        if ((res.code == 200)) {
          this.userId = res.data.userId;
          this.isSign = res.data.isSign;
        }
      });
    },
    //解决状态
    updateDemandStatus(id, demandStatus, Dobule) {
      let _params = {
        id,
        demandStatus,
      };
      updateDemandStatus(_params).then((res) => {
        console.log(res);
        if (res.code == 200) {
          if (Dobule) {
          } else {
            this.$message.success("修改成功");
          }
          if (Dobule) {
            this.deleteMaterialsDemand(this.delID);
          }
          this.GetSearchPageList();
        } else {
          this.$message.warning("修改失败");
        }
      });
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log("Received values of form: ", values);
          // if (values.creatDate != undefined) {
          //   var createTimeFrom = moment(values.creatDate[0]).format(
          //     "YYYY-MM-DD"
          //   );
          //   var createTimeTo = moment(values.creatDate[1]).format("YYYY-MM-DD");
          // }
          // if (values.endDate != undefined) {
          //   var expirationDateFrom = moment(values.endDate[0]).format(
          //     "YYYY-MM-DD"
          //   );
          //   var expirationDateTo = moment(values.endDate[1]).format(
          //     "YYYY-MM-DD"
          //   );
          // }
          this.ipagination.current = 1;
          this.formLine = {
            keyword: values.keyword,
            demandStatus: values.demandStatus,
            auditStatus: values.auditStatus,
            expiredType: values.expiredType,
          };
          console.log(this.formLine);
          this.GetSearchPageList();
        }
      });
    },
    clear() {
      this.createTimeFrom = "";
      this.createTimeTo = "";
      this.expirationDateFrom = "";
      this.expirationDateTo = "";
      // 清空表单
      this.form.resetFields();
      this.ipagination.current = 1;
      this.formLine = {};
      this.GetSearchPageList();
    },
    handleChange(value) {
      // console.log(`selected ${value}`);
    },
    onChange(date, dateString) {
      console.log(dateString);
      this.createTimeFrom = dateString[0];
      this.createTimeTo = dateString[1];
    },
    onChange1(date, dateString) {
      // console.log(date, dateString);
      this.expirationDateFrom = dateString[0];
      this.expirationDateTo = dateString[1];
    },
    //查看详情按钮的点击事件
    add() {
      if (this.isSign == 1) {
        this.$router.push("/usercenter/RequirementRelease");
      } else {
        this.$store.commit('setIsSign',true);
        // this.$message.warning('您需要完成信用承诺函签署再进行该操作。')
      }
    },
    seeEdit(record) {
      let id = record.id;
      this.$router.push({
        path: "/usercenter/NeedLook",
        query: { id },
      });
    },
    //编辑按钮的点就事件
    handleEdit(item) {
      // this.EditId = item.id;
      // this.$refs.Edit.visible = true;
      let id = item.id;
      this.$router.push({
        path: "/usercenter/MyNeedEdit",
        query: { id },
      });
    },
    //删除按钮的点击事件
    deleEdit(item) {
      var that = this;
      this.$confirm({
        title: "您确定要删除此信息吗？",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          // 点击确定
          that.deleteMaterialsDemand(item.id);
        },
        onCancel() {
          // 点击取消
          console.log("Cancel");
        },
      });
      // this.Status = item.demandStatusName
      // this.auditStatus = item.auditStatus
      // this.delID  = item.id
      // this.visible = true
    },
    // handleOk(e) {
    // let that = this
    // console.log(e);
    // if(this.checkNick==true){
    //   let demandStatus = 1
    //   this.updateDemandStatus(this.delID,demandStatus,'Dobule')
    //   // this.updateDemandStatus(this.delID,demandStatus).then(
    //   //   that.deleteMaterialsDemand(that.delID)
    //   // )

    // }else{
    //   this.deleteMaterialsDemand(this.delID);
    // }
    //   this.deleteMaterialsDemand(this.delID);

    //   this.visible = false;
    // },
    // handleChange1(e) {
    //   this.checkNick = e.target.checked;
    //   console.log(this.checkNick)
    // },
    Edit(item) {
      console.log(item);
      var that = this;
      this.$confirm({
        title: "是否确认已解决该需求?",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          // 点击确定
          let id = item.id;
          let demandStatus = 1;
          that.updateDemandStatus(id, demandStatus);
        },
        onCancel() {
          // 点击取消
          console.log("Cancel");
        },
      });
    },
    //删除
    deleteMaterialsDemand(_params) {
      deleteMaterialsDemand({ id: _params }).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.$message.success("删除成功");
          if (this.materialsDemand.length == 1) {
            // 如果只有最后一条就刷新上一页
            this.ipagination.current--;
          }
          if (this.ipagination.current < 1) {
            this.ipagination.current = 1;
          }

          this.GetSearchPageList();
        } else {
          this.$message.warning("删除失败");
        }
      });
    },

    // 分页搜索
    onPageChange(page, pageSize) {
      this.ipagination.current = page;
      this.GetSearchPageList();
    },
    // 页容量改变
    onSizeChange(current, pageSize) {
      this.ipagination.pageSize = pageSize;
      this.ipagination.current = current;
      this.GetSearchPageList();
    },
    // 获取需求列表
    GetSearchPageList() {
      let _params = {
        size: this.ipagination.pageSize,
        current: this.ipagination.current,
        userId: this.userId,
        createTimeFrom: this.createTimeFrom,
        createTimeTo: this.createTimeTo,
        expirationDateFrom: this.expirationDateFrom,
        expirationDateTo: this.expirationDateTo,
        orderTypes: 5, //更新时间倒序
        ...this.formLine,
      };
      GetSearchPageList(_params)
        .then((res) => {
          // console.log('=====================================详情')
          // console.log(res);
          if (res.code == 200) {
            this.materialsDemand = res.data.records;
            this.ipagination.total = res.data.total;
            // console.log(this.materialsDemand);
            this.materialsDemand.forEach((item) => {
              item.ishandleEdit = true;
              item.isdeleEdit = true;
              item.isEdit = true;
              if (item.auditStatus == 1) {
                //审核中
                item.ishandleEdit = false;
                item.isdeleEdit = false;
                item.isEdit = false;
                // console.log('审核中')
                if (item.showNotExpired == 1) {
                  //已过期
                  item.ishandleEdit = true;
                  item.isdeleEdit = true;
                  // item.isEdit = false;
                }
              } else if (item.auditStatus == 2) {
                //已通过
                item.ishandleEdit = true;
                item.isdeleEdit = true;
                // console.log('已审核')
                if (item.demandStatusName == "已解决") {
                  //已解决
                  item.ishandleEdit = false;
                  item.isEdit = false;
                } else if (item.demandStatusName == "未解决") {
                  //未解决
                  item.isdeleEdit = false;
                }
              } else if (item.auditStatus == 3) {
                // 未通过
                if (item.demandStatusName == "已解决") {
                  //已解决
                  item.isEdit = false;
                } else if (item.demandStatusName == "未解决") {
                  //未解决
                  item.isEdit = false;
                }
              }
            });
            console.log(this.materialsDemand);
          }
        })
        .catch((error) => {});
    },
  },
};
</script>

<style lang="less" scoped>
.MyNeed {
  padding: 16px 24px;
  background: #fff;
  .MyNeed-title {
    &:nth-child(1) {
      font-size: 22px;
      color: #303133;
    }
    .add-btn {
      margin-left: 16px;
      width: 60px;
      height: 32px;
      background-color: #ffffff;
      border-radius: 4px;
    }
  }

  .card-box {
    padding: 16px 19px;
    background-color: #f5f7fa;
    border-radius: 4px;
    margin-bottom: 24px;
  }

  .action {
    span {
      a {
        font-size: 14px;
        color: #188af1;
      }
    }
  }
  .operate-cls {
    display: grid;
    grid-template-columns: 75px 75px;
  }
}
</style>